package com.itheima.reggie_auto.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie_auto.dto.OrdersDto;
import com.itheima.reggie_auto.entity.*;
import com.itheima.reggie_auto.exception.CustomException;
import com.itheima.reggie_auto.mapper.OrdersMapper;
import com.itheima.reggie_auto.service.*;
import com.itheima.reggie_auto.util.BaseContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;


    @Override
    @Transactional
    public Page<OrdersDto> page(int page, int pageSize) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrdersDto> dtoPage = new Page<>();

        //构造条件  1.用户id   按下单时间降序
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId, BaseContext.getCurrentId());
        lqw.orderByDesc(Orders::getOrderTime);
        ordersMapper.selectPage(pageInfo, lqw);

        //数据对拷
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");

        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> ordersDtoList = records.stream().map(item -> {
            OrdersDto ordersDto = new OrdersDto();

            //数据对拷
            BeanUtils.copyProperties(item, ordersDto);
            //获取每一个订单的订单明细，
            List<OrderDetail> detailList = orderDetailService.getByOrderId(item.getId());
            ordersDto.setOrderDetails(detailList);

            return ordersDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(ordersDtoList);

        return dtoPage;
    }

    @Override
    @Transactional
    public void submit(Orders orders) {
        //分析：去支付就是生成点单数据，想订单表插入数据
        //先判断购物车是否有值，有东西才能生成订单，有地址才能生成订单，没有地址报错
        //1.根据用户Id查购物车  查地址

        Long userId = BaseContext.getCurrentId();
        //先判断购物车是否有值
        List<ShoppingCart> shoppingCarts = shoppingCartService.getAll();//根据id查购物车
        if (shoppingCarts == null && shoppingCarts.size() != 0) {
            //为空报客户端异常
            throw new CustomException("购物车不能为空");
        }
        //判断有无地址数据
        //默认地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);

        if (addressBook == null) {
            //地址为空报异常
            throw new CustomException("请先添加地址再下单");
        }

        //生成订单所需要的数据有 ，用户相关的 phone ,userName
        User user = userService.getById(userId);

        //生成Id
        long orderId = IdWorker.getId();

        // A. 获得当前用户id, 查询当前用户的购物车数据
        // B. 根据当前登录用户id, 查询用户数据
        // C. 根据地址ID, 查询地址数据
        // D. 组装订单明细数据, 批量保存订单明细
        // E. 组装订单数据, 批量保存订单数据
        // F. 删除当前用户的购物车列表数据

        //根据购物车数据  设置 购物车id ，菜品或者套餐名，图片菜品或者套餐id口味，数量，金额
        //先添加明细表，再添加订单表
        AtomicInteger atomicInteger = new AtomicInteger(0);
        List<OrderDetail> orderDetails = shoppingCarts.stream().map(item -> {

            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(item, orderDetail);
            //计算总金额
            atomicInteger.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;

        }).collect(Collectors.toList());

        //订单表
        Orders order = new Orders();
        order.setId(orderId);
        order.setNumber(String.valueOf(orderId));
        order.setStatus(2);
        order.setUserId(userId);
        order.setAddressBookId(addressBook.getId());
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        order.setPayMethod(orders.getPayMethod());
        order.setAmount(new BigDecimal(atomicInteger.get()));
        order.setRemark(orders.getRemark());
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setUserName(user.getName());
        order.setConsignee(addressBook.getConsignee());

        //向订单表插入数据
        ordersMapper.insert(order);
        //想订单明细表插入数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车
        shoppingCartService.clean();

    }

    /**
     * 再来一单
     *
     * @param orders
     */
    @Override
    @Transactional
    public void again(Orders orders) {
        //分析：前端只传订单id  我们要查出来原来购物车的数据 然后添加到购物车中即可

        //先把购物车清空再赋值一个新的
        shoppingCartService.clean();
        //根据订单Id查询订单明细
        List<OrderDetail> orderDetails = orderDetailService.getByOrderId(orders.getId());

        orderDetails.stream().map(item -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(item, shoppingCart);

            shoppingCart.setId(IdWorker.getId());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.add(shoppingCart);
            return shoppingCart;
        }).collect(Collectors.toList());
    }

    @Override
    public Page<Orders> pageInfo(int page, int pageSize, Long number, String beginTime, String endTime) {
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        //构造条件
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.like(number!=null,Orders::getNumber,number);
        lqw.between(StringUtils.isNotEmpty(beginTime)&&StringUtils.isNotEmpty(endTime),Orders::getOrderTime,beginTime
                ,endTime);
        lqw.orderByDesc(Orders::getOrderTime);
        ordersMapper.selectPage(pageInfo,lqw);
        return pageInfo;
    }

    @Override
    public void update(Orders orders) {
        LambdaUpdateWrapper<Orders> luw = new LambdaUpdateWrapper<>();
        luw.set(Orders::getStatus,orders.getStatus());
        luw.eq(Orders::getId,orders.getId());
        ordersMapper.update(orders,luw);
    }
}
